<template>
	<rui-pages :bar="bar">
		<rui-card>
			<rui-table :data="data" :columns="columns" :limit="limit" :total="total" @change="changeTable"></rui-table>
		</rui-card>
	</rui-pages>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onShow
	} from "@dcloudio/uni-app"
	import UsersModel from '@/db/UsersModel';
	import {
		settingStore
	} from '@/store';



	let setting = settingStore();

	let data = ref([])
	let page = ref(1)
	let total = ref(0)
	let limit = ref(9)

	let bar = [{
		name: "用户管理",
		icon: "users",
		url: "pages/user/index/index",
		promise: 13
	}, {
		name: "添加用户",
		icon: "adduser",
		url: "pages/user/register/register",
		promise: 13
	}]


	let columns = ref([{
			title: 'ID',
			field: 'id',
			width: 60,
			align: 'center'
		},
		{
			title: '昵称',
			field: 'nickname',
			align: 'left'
		},
		{
			title: '用户名',
			field: 'username',
			align: 'left'
		},
		{
			title: '用户权限',
			field: 'role',
			width: 100,
			align: 'center'
		},
		{
			title: '创建时间',
			align: 'center',
			field: 'created_at',
			width: 170
		},
		{
			title: '操作',
			align: 'center',
			tool: [
				"编辑", "删除"
			],
			width: 130
		}
	])

	onShow(() => {
		getData()
	})

	let users = new UsersModel();
	


	const changeTable = (e) => {
		console.log(e)
		if (e.type == 'page') {
			page.value = e.data
			getData()
		}
		if (e.type == 'tool') {
			if (e.event == '编辑') {
				editData(e.data)
			}
			if (e.event == '删除') {
				delData(e.data)
			}
		}
	}

	const delData = (data) => {
		console.log('delete', data)
		uni.showModal({
			title: '删除提示',
			content: '删除后不可恢复，您确定要是删除吗？',
			success: function(res) {
				if (res.confirm) {
					users.del({
						id: data.id
					}).then(res => {
						uni.showToast({
							title: "删除成功",
							icon: "success",
							success() {
								getData()
							}
						})
					})
				}
			}
		});
	}


	const editData = (data) => {
		// uni.navigateTo({
		// 	url: "/pages/user/info/info?id=" + data.id
		// })
		uni.$rui.route('/pages/user/info/info', {id: data.id})
	}

	const getRoleName = (id) => {
		for (let i = 0; setting.role.length > i; i++) {
			if (setting.role[i].id == id) {
				return setting.role[i].name;
			}
		}
	}

	const getData = () => {
		users.getPage(page.value, limit.value).then(res => {
			data.value = res.data.map(item => {
				item.role = getRoleName(item.role_id)
				return item;
			});
			total.value = res.count;
		}).catch(e => {})
	}
</script>

<style>

</style>